package com.cnkvha.trackcontestmgmt.contest;

import org.webbitserver.helpers.Base64;
import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;

public class Contest {

    public String name;

    public ContestTrackInfo[] tracks;

    public ContestState state = ContestState.STANDBY;
    public long start_time = -1; // in milli-seconds

    public int realtime_order_index = 0;

    // for deserialization
    public Contest() {
    }

    public Contest(String name) {
        this.name = name;
    }

    public Contest(String name, ContestTrackInfo[] tracks, ContestState state, long start_time) {
        this.name = name;
        this.tracks = tracks;
        this.state = state;
        this.start_time = start_time;
    }

    public static Contest readFromFile(File f) {
        try {
            return new Yaml().loadAs(new FileInputStream(f), Contest.class);
        } catch (Exception ex){
            ex.printStackTrace();
            return null;
        }
    }

    public int findIndexByName(String name) {
        if(tracks == null) return -1;
        for(int i = 0; i < tracks.length; i++) {
            if(tracks[i].name.equals(name)) {
                return i;
            }
        }
        return -1;
    }

    public String serializeIntoTCMData() {
        StringBuilder sb = new StringBuilder(name + ";");
        if(tracks != null && tracks.length > 0) {
            sb.append(tracks.length + ";");
            for (int i = 0; i < tracks.length; i++) {
                sb.append(tracks[i].serializeIntoTCMData());
                sb.append(";");
            }
        } else {
            sb.append("0;");
        }
        sb.append(state.name() + ";");
        sb.append(start_time);
        return Base64.encode(sb.toString().getBytes(StandardCharsets.UTF_8));
    }

    public void resetRuntimeData() {
        if(tracks != null) {
            for(ContestTrackInfo t : tracks) {
                t.resetRuntimeData();
            }
        }
        realtime_order_index = 0;
    }
}
